package com.crawler.actor

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import com.crawler.message.{TaskParamListMessage, TaskParamMessage}
import com.crawler.service.CrawlerService

/**
  * Created by tongtao.zhu on 2016/11/28.
  */
class CrawlerActor(taskCollectionRef: ActorRef) extends Actor with ActorLogging{
//  val crawlerService = CrawlerService.crawlerService

  override def postStop(): Unit = {
    log.info("结束一个CrawlerActor")
  }

  override def preStart(): Unit = {
    // 订阅集群事件
    log.info("开始一个CrawlerActor")
  }


  override def receive = {
    case TaskParamListMessage(tasks) => {
      val crawlerServiceRef = context.actorOf(Props[CrawlerService])
      crawlerServiceRef ! tasks
    }
    case lists: List[TaskParamMessage] =>
      val updateTasks = lists.filter(task => task.status == 1)
      val insertTasks = lists.filter(task => task.status == 0)
      log.info(s"开始更新${lists.size}个任务...")
      if (updateTasks.size > 0){
        taskCollectionRef ! TaskParamListMessage(updateTasks.toList)
      }
      val size = insertTasks.size/150 + 1
      for (i <- 0 to size){
        taskCollectionRef ! TaskParamListMessage(insertTasks.slice(i*150, i*150+150).toList)
      }
  }
}
